# coding
import email
import os
import base64
import codecs
import os
import email
from email.header import decode_header
import glob
import uuid
# 指定 EML 文件路径
# eml_file_path = 'C:/Users/summit/Desktop/广发/广发/广发邮件otc_operation@gf.com.cn/0814/2023年08月14日估值报告-锐天核心18（多空互换估值报告）.eml'
#
# # 创建目录以保存附件
# attachment_dir = 'attachments'
# os.makedirs(attachment_dir, exist_ok=True)

def decode_subject(header):
    decoded, charset = decode_header(header)[0]
    if isinstance(decoded, bytes):
        return decoded.decode(charset or 'utf-8')
    return decoded
def decode_str(s):
    value, charset = decode_header(s)[0]      #Returns a list of (string, charset) pairs
    if charset:
        value = value.decode(charset)
    return value


def add_uuid_to_filename(filename):
    # 生成 UUID
    unique_id = uuid.uuid4()
    # 分离文件名和扩展名
    base, ext = os.path.splitext(filename)
    # 创建新的文件名
    new_filename = f"{base}#{unique_id}{ext}"

    return new_filename

# 打开 EML 文件
def dow(attachment_dir,eml_file_path):
    os.makedirs(attachment_dir, exist_ok=True)
    with open(eml_file_path, 'rb') as eml_file:
        eml_message = email.message_from_binary_file(eml_file)

        # 获取邮件主题
        subject = decode_subject(eml_message['subject'])

        print(f"Subject: {subject}")

        # 遍历邮件中的每一个附件
        for part in eml_message.walk():
            if part.get_content_maintype() == 'multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue

                # 获取附件文件名
            filename  = part.get_filename()
            contType = part.get_content_type()

            if filename:
                h = email.header.Header(filename)
                dh = email.header.decode_header(h)     #对附件名称进行解码，
                #Returns a list of (string, charset) pairs containing each of the decoded parts of the header
                filename = dh[0][0]
                if dh[0][1]:
                    filename = decode_str(str(filename,dh[0][1]))#将附件名称可读化
                    print(filename)
            if filename:
                # 构建附件保存路径
                attachment_path = os.path.join(attachment_dir, add_uuid_to_filename(filename.replace("/","")))

                # 保存附件到指定路径
                with open(attachment_path, 'wb') as attachment_file:
                    attachment_file.write(part.get_payload(decode=True))

                print(f"Saved attachment: {filename}")
def download(dir,file_path):
    with open(file_path, 'r') as file:
        eml_content = file.read()
    msg = email.message_from_string(eml_content)
    flag = True
    for part in msg.get_payload():
        if part.get_content_type() == 'application/octet-stream':
            flag = False
            attachment = part.get_filename()
            print(attachment)
            attachment_list = attachment.split('?')
            if len(attachment_list) != 1:
                rep = "=?"+attachment_list[1]+"?"+attachment_list[2]+"?"
                file_name =attachment.replace(rep,"")
                attachment = base64.b64decode(file_name).decode(attachment_list[1])

            if attachment:
                    # 保存附件到本地
                    with open(dir+attachment, 'wb') as f:
                        f.write(part.get_payload(decode=True))
                    print(f'保存附件: {attachment}')
    if flag:
        print("文件无附件%s", file_path)
def find_eml_files(directory):
    # 使用 glob 递归搜索 .eml 文件
    eml_files = glob.glob(os.path.join(directory, '**', '*.eml'), recursive=True)
    return eml_files
# if __name__ == '__main__':
#     download("./","C:/Users/summit/Desktop/广发/广发/广发邮件otc_operation@gf.com.cn/0814/2023年08月14日估值报告-锐天核心18（多空互换估值报告）.eml")
if __name__ == '__main__':
    path= 'C:/Users/summit/Desktop/attr'

    eml_files = find_eml_files(path)

    for file in eml_files:
        print(os.path.dirname(file))
        gener_dir = os.path.dirname(file).replace('attr','attr1') + "/"
        dow(gener_dir, file)
    # files= os.listdir(path)
    # s = []
    # for file in files: #遍历文件夹
    #     path1 = path+"/"+file
    #     dir = "/"+file+"/"
    #     files1 = os.listdir(path1)
    #     for file1 in files1:
    #         path2 = path1+"/"+file1
    #         dir = dir +file1
    #         files2 = os.listdir(path2)
    #         for file2 in files2:
    #             s.append(path2+"/"+file2)
    #             print(path2+"/"+file2)
    #             other = 'C:/Users/summit/Desktop/22'
    #             print(other+dir)
    #             if not os.path.exists(other+dir):
    #                 os.makedirs(other+dir, mode=0o777)
    #             dow(other+dir+"/",path2+"/"+file2)
